
//#include "head.h"
//#include <stdio.h>
#include <signal.h>

#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/MySQLResult.h>
using std::cout;
using std::endl;
using std::string;

//
//初始化计数器的值为1
static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf(">> sig num %d is comming\n", num);
    //调用一次done方法，计数器的值减1
    waitGroup.done();
}

void mysqlCallback(WFMySQLTask * mysqltask)
{
    printf("mysqlCallback is running.\n");
    //0. 对任务的状态进行检测
    int state = mysqltask->get_state();
    int error = mysqltask->get_error();
    if(state != WFT_STATE_SUCCESS) {
        printf("error msg: %s\n", WFGlobal::get_error_string(state, error));
        return;
    }
    //1. 对SQL进行语法检测
    auto resp = mysqltask->get_resp();
    if(resp->get_packet_type() == MYSQL_PACKET_ERROR) {
        printf("ERROR %d: %s\n", resp->get_error_code(),
                                 resp->get_error_msg().c_str());
    }

    //2. 对结果集进行遍历
    protocol::MySQLResultCursor cursor(resp);
    if(cursor.get_cursor_status() == MYSQL_STATUS_OK) {
        //2.1写操作正常执行
        printf("Query OK, %llu rows affected.\n", cursor.get_affected_rows());
    } else if(cursor.get_cursor_status() == MYSQL_STATUS_GET_RESULT) {
        //读操作正常执行
        //2.2 先读取字段信息
        const protocol::MySQLField * const * arr = cursor.fetch_fields();
        for(int i = 0; i < cursor.get_field_count(); ++i) {
            printf("name: %s, type: %s, tbl: %s, db: %s\n",
                    arr[i]->get_name().c_str(),
                    datatype2str(arr[i]->get_data_type()),
                    arr[i]->get_table().c_str(),
                    arr[i]->get_db().c_str());
        }
        //2.3 在读取数据信息
        std::vector<std::vector<protocol::MySQLCell>> rows;
        cursor.fetch_all(rows);
        printf("\n%ld rows in set.\n", rows.size());
        //使用增强for循环时，通过auto关键字自动推导时，
        //一定要加上& 引用符号；否则就会对每一个元素进行复制
        for(auto & row : rows) {
            for(auto & cell : row) {
                if(cell.is_int()) {
                    printf("[%d] ", cell.as_int());
                } else if(cell.is_string()) {
                    printf("[%s] ", cell.as_string().c_str());
                }
            }
            printf("\n");
        }
    }
}

void test0()
{
    signal(SIGINT, sighandler);
    
    string url("mysql://root:1234@localhost");
    auto mysqlTask = WFTaskFactory::create_mysql_task(url, 1, mysqlCallback);
    string sql = "select * from cloudisk.tbl_user_token";
    mysqlTask->get_req()->set_query(sql);
    mysqlTask->start();

    //当调用wait方法会阻塞当前线程
    waitGroup.wait();

    cout << "test0 exit" << endl;
}


int main()
{
    test0();
    return 0;
}

